package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
)

func main() {
	dialOption := redis.DialPassword("xiaoyunshi")
	conn, err := redis.Dial("tcp", "127.0.0.1:6379", dialOption)
	if err != nil {
		conn.Close()
		fmt.Println("连接出错:", err)
		return
	}
	fmt.Println("连接成功")
	SendTest(conn)
	//setTest(conn, err)
	//hashTest(conn, err)
	defer conn.Close()
}
func SendTest(conn redis.Conn) {
	err2 := conn.Send("set", "goTest", 2)
	if err2 != nil {
		fmt.Println("err", err2)
	}
	err2 = conn.Send("hset", "go-h", "name", "2")
	if err2 != nil {
		fmt.Println("err", err2)
	}
	_ = conn.Flush()
	receive, err := conn.Receive()
	for err == nil && receive != nil {
		fmt.Println("receive:", receive)
		receive, err = conn.Receive()
	}
}

// hash 测试
func hashTest(conn redis.Conn, err error) {
	HSet(conn, "go-h", "name", "wang")
	hval, err := HGet(conn, "go-h", "name")
	if err != nil {
		fmt.Println("hget error", err)
		return
	}

	res, _ := redis.String(hval, err)
	fmt.Println("hget go-h name:", res)
}

// get - set
func setTest(conn redis.Conn, err error) {
	Set(conn, "goTest", 1)
	val, err := Get(conn, "goTest")
	if err != nil {
		fmt.Println("get error", err)
		return
	}
	valFinal, _ := redis.Int(val, err)
	fmt.Println("get goTest:", valFinal)
	conn.Send()
}

// 执行 set 命令
func Set(conn redis.Conn, key string, value interface{}) {
	reply, err := conn.Do("set", key, value)
	if err != nil {
		fmt.Printf("exec error...key:%v\t value:%v\n", key, value)
		return
	}
	if reply != nil {
		fmt.Printf("set %v %v ,return %v\n", key, value, reply)
	}
}

// hset
func HSet(conn redis.Conn, key string, hashKey string, value interface{}) {
	reply, err := conn.Do("hset", key, hashKey, value)
	printReplyAndError(err, key, value, reply)
}

//执行 get 命令
func Get(conn redis.Conn, key string) (interface{}, error) {
	return conn.Do("get", key)
}
func HGet(conn redis.Conn, key string, hashKey string) (interface{}, error) {
	return conn.Do("hget", key, hashKey)
}
func printReplyAndError(err error, key string, value interface{}, reply interface{}) {
	if err != nil {
		fmt.Printf("exec error...key:%v\t value:%v\n", key, value)
		return
	}
	if reply != nil {
		fmt.Printf("set %v %v ,return %v\n", key, value, reply)
	}

}
